package controllers

import (
	"WORKSPACE/models"
	"WORKSPACE/pkg/app"
	"WORKSPACE/pkg/e"
	"WORKSPACE/services"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
)

func GetAlldepartment(c *gin.Context)  {
	err, info, total := services.GetAlldepartment()
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total},"查询成功")
}

func Deldepartment(c *gin.Context){
	id := "-1"
	if arg := c.Query("Dno"); arg != "" {
		id = arg
		fmt.Println(id)
	}
	if id == "-1"{
		app.INFO(c,30001,"参数错误")
		return
	}
	err := services.Deldepartment(id)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"删除成功")
}

func Updatedepartment(c *gin.Context){
	data, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(data, &m)

	dname := m["Dname"]
	dno := m["Dno"]
	dman :=m["Dman"]



	if m["Dno"] == ""{
		app.INFO(c, 30000, "参数非法")
		return
	}
	err := services.Updatedepartment(models.Department{ Dname: dname, Dno: dno,  Dman: dman})
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"更新成功！")
}

func Adddepartment(c *gin.Context){
	data, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(data, &m)

	dname := m["Dname"]
	dno := m["Dno"]
	dman :=m["Dman"]

	if m["Dno"] == ""{
		app.INFO(c, 30000, "参数非法")
		return
	}
	err := services.Adddepartment(models.Department{ Dname: dname, Dno: dno,  Dman: dman})
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"添加成功！")
}